package com.brainshare.common.utils;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SmsUtils
{
    public static final Logger logger = LoggerFactory.getLogger(SmsUtils.class);
//    AccessKey ID
//    LTAI5tBSRtmew5n6N4NPU2NS
//
//    AccessKey Secret
//    v5V8EiT7SUz0OTUA9LbfCiU7CXyKbb

    public static String ACCESS_KEY_ID = "LTAI5tBSRtmew5n6N4NPU2NS";

    public static String ACCESS_KEY_SECRET = "v5V8EiT7SUz0OTUA9LbfCiU7CXyKbb";

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }


    public static boolean sendAliyunSms(String phone, String smsCode)
    {
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        try
        {
            com.aliyun.dysmsapi20170525.Client client = createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setSignName("脑常青")  //短信title测试
                    .setTemplateCode("SMS_461355198")  //短信内容体修改
                    .setPhoneNumbers(phone)
                    .setTemplateParam("{\"code\":" + smsCode + "}");
//                    .setTemplateParam("{\"code\":\"1234\"}");  //短信内容
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            logger.info(JSON.toJSONString(sendSmsResponse.getBody()));
            return true;
        } catch (TeaException error)
        {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            logger.error(error.getMessage());
            return false;
        } catch (Exception _error)
        {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            logger.error(error.getMessage());
            return false;
        }
    }
}
